package com.itheima.reggie.controller;

import com.itheima.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author gakki
 * @create 2022/5/2 18:55
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.basePath}")
    private String basePath;

    /**
     * 文件上传至服务器
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> imageUpload(MultipartFile file) {
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //UUID生成新的文件名
        String fileName = UUID.randomUUID().toString();
        fileName += originalFilename.substring(originalFilename.lastIndexOf("."));

        //判断文件目录是否存在，不存在重新创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //临时文件转储为本地文件
        try {
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(fileName);
    }

    /**
     * 图片文件回显
     * @param response
     * @param name
     */
    @GetMapping("/download")
    public void imageDownload(HttpServletResponse response, String name) {
        log.info("图片回显：{}", name);
        try {
            //字节输入流
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));
            //输出流，文件回写到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            //设置上传文件格式
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
